
import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:permission_handler/permission_handler.dart';

class AudioManager {
  RtcEngine? _engine;

  Future<void> initAgora() async {
    _engine = await RtcEngine.create("e8da53ecd1784eac8f4a24a25deb31f7");
    _engine?.enableAudio();
    _engine?.setEventHandler(RtcEngineEventHandler(
      joinChannelSuccess: (channel, uid, elapsed) {
        print("joinChannelSuccess: $channel, uid: $uid");
      },
      userJoined: (uid, elapsed) {
        print("remote user joined: uid: $uid");
      },
      userOffline: (uid, reason) {
        print("userOffline: uid: $uid , reason: $reason");
      },
    ));
  }
  
  Future<void> requestMicrophonePermission() async {
    var status = await Permission.microphone.request();
    if (!status.isGranted) {
      throw 'Microphone permission not granted.';
    }
  }

  void joinChannel() async {
    print("joinChannel");
    // await _engine?.joinChannel("your_token", "your_channel_name", null, 0);
    await _engine?.joinChannel(null, "my_test_channel", null, 0);
  }
  void leaveChannel() async {
    await _engine?.leaveChannel();
  }
  void dispose() async {
    await _engine?.destroy();
  }
}

class SpeechManager {
  stt.SpeechToText _speech = stt.SpeechToText();
  String _lastWords = '';

  Future<void> initSpeech() async {
    bool available = await _speech.initialize();
    if (available) {
      _speech.listen(onResult: (result) {
        _lastWords = result.recognizedWords;
        print("Speech result: $_lastWords");
      });
    }
  }

  void startListening() {
    _speech.listen(onResult: (result) {
      _lastWords = result.recognizedWords;
      // 更新UI或处理识别到的文本
    });
  }

  void stopListening() {
    _speech.stop();
  }

}

class MyAudioPage extends StatefulWidget {
  @override
  _MyAudioPageState createState() => _MyAudioPageState();
}

class _MyAudioPageState extends State<MyAudioPage> {
  final AudioManager _audioManager = AudioManager();

  @override
  void initState() {
    super.initState();
    _audioManager.initAgora().then((_) {
      _audioManager.requestMicrophonePermission().then((_) {
        // 额外的设置或进一步的操作，如加入频道等
        print("音频");
      }).catchError((error) {
        // 处理错误，比如提示用户权限被拒绝
        print(error);
      });
    });
  }

  @override
  void dispose() {
    _audioManager.dispose();  // 清理资源
    super.dispose();
  }

   @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Audio Call"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () async {
                try {
                  await _audioManager.requestMicrophonePermission();
                  print("1111111");
                  _audioManager.joinChannel();  // 加入频道
                } catch (e) {
                  // 显示错误消息，例如权限被拒绝
                  showDialog(
                    context: context,
                    builder: (_) => AlertDialog(
                      title: Text('Error'),
                      content: Text(e.toString()),
                      actions: [
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(),
                          child: Text('OK'),
                        ),
                      ],
                    ),
                  );
                }
              },
              child: Text('Join Channel1'),
            ),
            ElevatedButton(
              onPressed: () {
                _audioManager.leaveChannel();  // 离开频道
              },
              child: Text('Leave Channel1'),
            ),
          ],
        ),
      ),
    );
  }

}
